import sys, os.path
sys.path.append('../external')

 
from thrift.transport import TTransport,TSocket
from thrift.Thrift import *
from thrift.server import *
from thrift.protocol import TBinaryProtocol, TProtocol,TCompactProtocol
from ServerService import *
from ServerServiceImp import *
from  config import Config

try:
  from thrift.protocol import fastbinary
except:
  fastbinary = None

def parseOpts():
	import argparse
	parser = argparse.ArgumentParser(prog='HiroSQL',
						description='HiroSQL Server Parameters',
						epilog="Note: Config file is another helpful place to put startup options")						
	parser.add_argument('-u', '--user', help='Run the server as the user having the name user_name')
	parser.add_argument('-p', '--port', type=int, help='''The port number to use when listening for TCP/IP connections.
						The port number must be 1024 or higher unless the server is started by the root system user''')
	parser.add_argument('-d', '--datadir', help='The path to the data directory.')
	parser.add_argument('--logdir', help='The path to the log directory.')
	parser.add_argument('-g', '--generallog', action='store_true', 
						help='Specify the initial general log state. By Default, the log is disabled')
	parser.add_argument('-q', '--querylog', action='store_true', 
						help='Specify the query log state. By Default, the log is disabled')
	parser.add_argument('-e', '--engine', help='Set the default storage engine (table type) for tables')
	parser.add_argument('-c', '--config', help='New config file to overwrite default config file')
	parser.add_argument('--initfile', type=argparse.FileType('r'), 
						help='The server executes the contents of the file named by this option at startup')

	parser.add_argument('--version', action='version', version='%(prog)s 0.1')
	parser.add_argument('-#','--debug', help='print more detailed debug information')

	args = parser.parse_args()
	return args
  
def rewriteConf(args):
	varsdict = vars(args)
	for item in varsdict:
		Config.defaultServerSetting[item] = varsdict[item]

	
	
	
	
class HiroSQLD:
  def __init__(self,port):
	self.port = port
  def Start(self):
	port =self.port
	serverTransport =TSocket.TServerSocket(port)
	processor = Processor(ServiceImp())
	factory =TBinaryProtocol.TBinaryProtocolFactory()
	server = TServer.TThreadedServer(processor,serverTransport,TTransport.TBufferedTransportFactory(),factory)
	server.serve()


	
if __name__ == '__main__':

  setattr(__builtins__, 'Config', Config)
  args = parseOpts()
  
  if args.config:  
	confIns=Config(args.config)
  else:
	confIns=Config()
  confIns.loadServer()
  
  args = parseOpts()

  
  svr = HiroSQLD(Config.defaultServerSetting['port'])
  svr.Start()
  
  
  
  